﻿using System;
using System.Net.Mail;
using System.IO;

using SsrsRenderStudio.Configuration;

namespace SsrsRenderStudio.Renderer.Output.Version2010
{
    public sealed class EmailOutput : Output
    {
        private string _destination;
        private string _fileExt;
        private string _contentType;
        private string _msg ="";

        public EmailOutput(byte[][] renderReport, string destination, string fileExtension, string contentType) : base(renderReport)
        {
            _destination = destination;
            _fileExt = fileExtension;
            _contentType = contentType;
        }

        public override void Process()
        {
            SendMail();  
        }

        public void AppendBody(string msg)
        {
            _msg += msg;
        }

        private void SendMail()
        {
            SmtpInfo info = ConfigurationManager.SmtpSettings();

            if (info != null)
            {
                //TODO: throw exception
            }

            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient(info.SmtpHost);

            mail.From = new MailAddress(info.FromAddress, info.FromDisplayName);
            mail.To.Add(_destination);
            mail.Subject = "Your Report";
            mail.Body = "See Attachment.\n" + _msg;
            mail.IsBodyHtml = false;

            //TODO: multiple page support
            MemoryStream ms = new MemoryStream(_renderedReport[0]);
            Attachment att = new Attachment(ms, "attachment." + _fileExt, _contentType);
            mail.Attachments.Add(att);

            SmtpServer.Send(mail);
            
            
        }
       
    }
}
